package com.aynu.gulimall.ware.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.aynu.common.exception.NoStockException;
import com.aynu.common.to.mq.OrderTo;
import com.aynu.common.to.mq.StockDetailTo;
import com.aynu.common.to.mq.StockLockedTo;
import com.aynu.common.utils.R;
import com.aynu.gulimall.ware.entity.WareOrderTaskDetailEntity;
import com.aynu.gulimall.ware.entity.WareOrderTaskEntity;
import com.aynu.gulimall.ware.feign.OrderFeignService;
import com.aynu.gulimall.ware.feign.ProductFeignService;
import com.aynu.gulimall.ware.service.WareOrderTaskDetailService;
import com.aynu.gulimall.ware.service.WareOrderTaskService;
import com.aynu.gulimall.ware.vo.*;
import com.mysql.cj.util.StringUtils;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.aynu.common.utils.PageUtils;
import com.aynu.common.utils.Query;

import com.aynu.gulimall.ware.dao.WareSkuDao;
import com.aynu.gulimall.ware.entity.WareSkuEntity;
import com.aynu.gulimall.ware.service.WareSkuService;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

@Service("wareSkuService")
@Slf4j
public class WareSkuServiceImpl extends ServiceImpl<WareSkuDao, WareSkuEntity> implements WareSkuService {

    @Resource
    WareSkuDao wareSkuDao;

    @Resource
    ProductFeignService productFeignService;

    @Autowired
    private WareOrderTaskService wareOrderTaskService;

    @Autowired
    private WareOrderTaskDetailService wareOrderTaskDetailService;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private OrderFeignService orderFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        /*skuId:
        wareId:*/
        QueryWrapper<WareSkuEntity> wrapper = new QueryWrapper<>();
        String skuId = (String) params.get("skuId");
        if (!StringUtils.isEmptyOrWhitespaceOnly(skuId))
        {
            wrapper.eq("sku_id",skuId);
        }
        String wareId = (String) params.get("wareId");
        if (!StringUtils.isEmptyOrWhitespaceOnly(wareId))
        {
            wrapper.eq("ware_id",wareId);
        }
        IPage<WareSkuEntity> page = this.page(
                new Query<WareSkuEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    //增加或修改商品库存
    @Override
    public void addStock(Long skuId, Integer skuNum, Long wareId) {
        // 如果没有这个库存记录,如果有则修改库存
        List<WareSkuEntity> wareSkuEntities = wareSkuDao.selectList(
                new QueryWrapper<WareSkuEntity>().eq("sku_id", skuId).eq("ware_id", wareId));
        if (wareSkuEntities == null || wareSkuEntities.size()==0){
            WareSkuEntity wareSkuEntity = new WareSkuEntity();
            wareSkuEntity.setSkuId(skuId);
            wareSkuEntity.setWareId(wareId);
            //TODO 远程调用sku名字,如果失败整个事务无需回滚
            /* TODO 出现异常事务不回滚的操作
            *1、自己try-catch
            *2、还有什么办法，使出现错误不回滚？高级篇
            * */

            try {
                R info = productFeignService.info(skuId);
                Map<String,Object> skuInfo = (Map<String, Object>) info.get("skuInfo");
                if (info.getCode()==0){
                    wareSkuEntity.setSkuName((String) skuInfo.get("skuName"));
                }
            }catch (Exception e){

            }
            wareSkuEntity.setStock(skuNum);
            this.save(wareSkuEntity);
        }else {
            wareSkuDao.addStock(skuId,skuNum,wareId);
        }
    }

    @Override
    public List<SkuHasStockVo> getSkuHasStock(List<Long> skuIds) {
        return skuIds.stream().map(skuId->{
            SkuHasStockVo skuHasStockVo = new SkuHasStockVo();

            //查询当前sku总库存量
            Long count = baseMapper.getSkuStock(skuId);
            if (count==null){
                log.error("sku信息为空，skuId："+skuId);
                skuHasStockVo.setSkuId(skuId);
                skuHasStockVo.setHasStock(false);
            }else {
                skuHasStockVo.setSkuId(skuId);
                skuHasStockVo.setHasStock(count > 0);
            }
            return skuHasStockVo;
        }).collect(Collectors.toList());
    }

    /**
     * 为某个订单锁定库存
     *
     * 库存解锁的场景
     * 1）、下订单成功，订单过期没有支付，被系统自动取消、被用户手动取消
     * 2）、下单成功，库存锁定成功，接下来的业务调用失败，导致订单回滚
     * 3）
     *
     * @param vo
     * @return
     */
    @Override
    @Transactional
    public Boolean orderLock(WareSkuLockVo vo) {

        /**
         * 保存库存工作单详情信息
         * 追溯
         */
        WareOrderTaskEntity wareOrderTaskEntity = new WareOrderTaskEntity();
        wareOrderTaskEntity.setOrderSn(vo.getOrderSn());
        wareOrderTaskEntity.setCreateTime(new Date());
        wareOrderTaskService.save(wareOrderTaskEntity);

        //1、按照下单的收货地址，找到一个就近仓库，锁定库存
        //2、找到每个商品在哪个仓库都有库存
        List<OrderItemVo> locks = vo.getLocks();

        List<SkuWareHasStock> collect = locks.stream().map((item) -> {
            SkuWareHasStock stock = new SkuWareHasStock();
            Long skuId = item.getSkuId();
            stock.setSkuId(skuId);
            stock.setNum(item.getCount());
            //查询这个商品在哪个仓库有库存
            List<Long> wareIdList = wareSkuDao.listWareIdHasSkuStock(skuId);
            stock.setWareId(wareIdList);

            return stock;
        }).collect(Collectors.toList());

        //2、锁定库存
        for (SkuWareHasStock hasStock : collect) {
            boolean skuStocked = false;
            Long skuId = hasStock.getSkuId();
            List<Long> wareIds = hasStock.getWareId();

            if (org.springframework.util.StringUtils.isEmpty(wareIds)) {
                //没有任何仓库有这个商品的库存
                throw new NoStockException(skuId);
            }

            //1、如果每一个商品都锁定成功,将当前商品锁定了几件的工作单记录发给MQ
            //2、锁定失败。前面保存的工作单信息都回滚了。发送出去的消息，即使要解锁库存，由于在数据库查不到指定的id，所有就不用解锁
            for (Long wareId : wareIds) {
                //锁定成功就返回1，失败就返回0
                Long count = wareSkuDao.lockSkuStock(skuId,wareId,hasStock.getNum());
                if (count == 1) {
                    skuStocked = true;
                    //保存库存工作单详情
                    WareOrderTaskDetailEntity taskDetailEntity = new WareOrderTaskDetailEntity(
                            null,skuId,"",hasStock.getNum(),wareOrderTaskEntity.getId(),wareId,1);
                    wareOrderTaskDetailService.save(taskDetailEntity);

                    //TODO 告诉MQ库存锁定成功
                    StockLockedTo lockedTo = new StockLockedTo();
                    lockedTo.setWareTaskId(wareOrderTaskEntity.getId());
                    StockDetailTo detailTo = new StockDetailTo();
                    BeanUtils.copyProperties(taskDetailEntity,detailTo);
                    lockedTo.setDetail(detailTo);
                    rabbitTemplate.convertAndSend("stock-event-exchange","stock.locked",lockedTo);
                    break;
                } else {
                    //当前仓库锁失败，重试下一个仓库
                }
            }

            if (!skuStocked) {
                //当前商品所有仓库都没有锁住
                throw new NoStockException(skuId);
            }
        }

        //3、肯定全部都是锁定成功的
        return true;
    }

    /**
     * 自动解锁库存
     *
     * 存在的问题：如果解锁库存失败，需要多次尝试，但是消息队列中消息自动删除
     * 原因：消息自动应答
     * 解决：取消消息自动应答，改为手动应答
     *
     *
     * @param stockLockedTo
     */
    @Override
    @Transactional
    public void unLockStock(StockLockedTo stockLockedTo) {
        //库存工作单的id
        StockDetailTo detail = stockLockedTo.getDetail();
        //库存工作单详情id
        Long id = detail.getId();
        //解锁
        //1、查询数据库关于这个订单的锁库存工作单消息
        //如果有：证明库存锁定成功
        //解锁：订单情况
        //      1、没有这个订单，表示创建订单时存在异常，回滚了
        //      2、没有有这个订单，则如果订单的状态为已取消，则需要解锁库存，没取消不能解锁库存
        //如果没有：库存锁定失败了，事务进行回滚，无需操作
        WareOrderTaskDetailEntity detailEntity = wareOrderTaskDetailService.getById(id);
        if (detailEntity!=null){
            //解锁
            //库存工作单id
            Long taskId = detailEntity.getTaskId();
            WareOrderTaskEntity taskEntity = wareOrderTaskService.getById(taskId);
            String orderSn = taskEntity.getOrderSn();
            log.info("调用远程服务查询订单信息，订单号{}",orderSn);
            R r = orderFeignService.getOrderStatus(orderSn);
            if (r.getCode()==0){
                OrderVo orderVo = r.getData(new TypeReference<OrderVo>() {});
                //如果订单不存在，则表示订单在锁定库存后，出现异常进行回滚了，也需要解锁库存 || 订单已被取消  需要解锁库存
                if (orderVo == null || orderVo.getStatus() == 4) {
                    //如果库存工作单的状态为已锁定但是未解锁
                    if (detailEntity.getLockStatus() == 1) {
                        //解锁库存
                        unLockStock(detailEntity.getSkuId(), detailEntity.getWareId(), detailEntity.getSkuNum(), detailEntity.getId());
                    }
                }else {
                    //无需解锁
                }
            }else {
                //需要重新解锁
                throw new RuntimeException("远程调用查询订单信息失败");
            }
        }else {
            //无需解锁
        }
    }

    /**
     * 防止服务器卡顿，导致订单信息一直改不了，库存信息新到期，查订单时为新建状态，什么都不做就走了
     * 导致卡顿的订单，永远无法解锁库存
     * @param orderTo
     */
    @Override
    @Transactional
    public void unLockStock(OrderTo orderTo) {
        //订单id
        String orderSn = orderTo.getOrderSn();
        //查询最新的库存工作单,防止重复解锁库存
        WareOrderTaskEntity taskEntity = wareOrderTaskService.getOrderTaskByOrderSn(orderSn);
        //库存工作单id
        Long id = taskEntity.getId();
        //按照工作单找到没有解锁的库存，进行解锁
        List<WareOrderTaskDetailEntity> list = wareOrderTaskDetailService.
                list(new QueryWrapper<WareOrderTaskDetailEntity>()
                .eq("task_id", id)
                .eq("lock_status", 1));
        //解锁库存
        for (WareOrderTaskDetailEntity detailEntity : list) {
            unLockStock(detailEntity.getSkuId(),detailEntity.getWareId(),detailEntity.getSkuNum(),detailEntity.getId());
        }
    }

    /**
     * 解锁库存，减去锁定的库存数
     * @param skuId
     * @param wareId
     * @param num
     * @param taskDetailId
     */
    private void unLockStock(Long skuId,Long wareId,Integer num,Long taskDetailId){
        //减去被锁定的库存
        log.info("库存工作单id:{}，skuId:{},wareId:{},解锁{}个库存",taskDetailId,skuId,wareId,num);
        wareSkuDao.unLockStock(skuId,wareId,num);
        //更新库存工作单的状态
        WareOrderTaskDetailEntity detailEntity = new WareOrderTaskDetailEntity();
        detailEntity.setId(taskDetailId);
        //修改为已解锁
        detailEntity.setLockStatus(2);
        log.info("库存工作单id:{}，修改状态为已解锁",taskDetailId);
        wareOrderTaskDetailService.updateById(detailEntity);
    }

    @Data
    static
    class SkuWareHasStock {
        private Long skuId;
        private Integer num;
        private List<Long> wareId;
    }

}